package com.capinfo.commons.project.web.controller.manage;

import java.util.List;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.capinfo.accumulation.web.Constants;
import com.capinfo.commons.project.model.security.SystemResource;
import com.capinfo.commons.project.service.security.SystemResourceService;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.util.CookieBuilder;
import com.capinfo.framework.web.util.WebRequestUtils;

@Controller
public class IndexController {
	
	private static final Log logger = LogFactory.getLog(IndexController.class); 

	@Autowired
	private SystemResourceService systemResourceService;

	/**
	 * 首页页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/manage/index.shtml")
	public ModelAndView index(NativeWebRequest request) {
		
		ModelAndView mav = new ModelAndView("/framework/easyui/index/main");
		
		mav.addObject("categoryMenus", systemResourceService.getCategoryMenus());
		

		String contextPath = null;
		Object nativeRequest = request.getNativeRequest();
		if( nativeRequest instanceof HttpServletRequest ) {
			
			contextPath = ((HttpServletRequest) nativeRequest).getSession().getServletContext().getContextPath();
		}
		Object nativeResponse = request.getNativeResponse();
		if( nativeResponse instanceof ServletResponse ) {

			HttpServletResponse response = (HttpServletResponse) nativeResponse;

			response.addCookie(CookieBuilder.build(Constants.COOKIE_NAME_CLIENT_INFO, String.valueOf(RandomUtils.nextInt(100)), -1, contextPath));
		}

		return mav;
	}
	
	/**
	 * 读取用户左侧访问资源
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/manage/left.shtml")
	public ModelAndView left(NativeWebRequest request) {

		ModelAndView mav = new ModelAndView("/framework/easyui/index/left");
		
		List<SystemResource> resources = null;
		try {
			
			resources = systemResourceService.getDisplayChildren(Long.parseLong(request.getParameter("resourceId")));
		} catch (Exception e) {
			
			LogUtils.debugException(logger, e);
		}
		mav.addObject("showMenus", resources);
		
		return mav;

	}

}
